#include "../../common/dispatcher.hpp"
#include "../../server/rpc_router.hpp"

void Add(const Json::Value& req, Json::Value& rsp)
{
    int num1 = req["num1"].asInt();
    int num2 = req["num2"].asInt();
    rsp = num1 + num2;
}

void test_basic()
{
    // 1.向RpcRouter注册服务
    auto router = std::make_shared<jsonrpc::server::RpcRouter>();
    std::unique_ptr<jsonrpc::server::SDescribeFactory> desc_factory(new jsonrpc::server::SDescribeFactory());
    desc_factory->setMethod("Add");
    desc_factory->setParamsDescribe("num1", jsonrpc::server::VType::INTEGRAL);
    desc_factory->setParamsDescribe("num2", jsonrpc::server::VType::INTEGRAL);
    desc_factory->setReturenType(jsonrpc::server::VType::INTEGRAL);
    desc_factory->setServiceCallBack(Add);

    router->registerMethod(desc_factory->build());
    
    // 2.向Dispatcher注册消息类型对应的回调 -- onRpcRequest处理(当收到rpc请求后, 去找对应rpc服务, 调用对应回调函数) (该服务从服务注册来)
    auto dispatcher = std::make_shared<jsonrpc::Dispatcher>();
    auto cb = std::bind(&jsonrpc::server::RpcRouter::onRpcRequest, router.get(), std::placeholders::_1, std::placeholders::_2);
    dispatcher->registerHandler<jsonrpc::RpcRequest>(jsonrpc::MType::REQ_RPC, cb); 

    // 3.将Dispatcher模块的onMessage设置给server的消息回调 -- (消息来了调用onMessage --> 根据消息类型找到onRpcRequest -->调用onRpcRequest )
    auto server = jsonrpc::ServerFactory::create(9090);
    auto message_cb = std::bind(&jsonrpc::Dispatcher::onMessage, dispatcher.get(), std::placeholders::_1, std::placeholders::_2);
    server->setMessageCallback(message_cb);
    server->start();
}

int main()
{
    test_basic();
    return 0;
}